/* Advanced mouse simulation patch by ng
 * Backward compatible.
 */

#include "SDL_config.h"

#include "SDL_events.h"
#include "../SDL/src/events/SDL_mouse_c.h"
#include "../SDL/src/video/android/SDL_androidtouch.h"


#define ACTION_DOWN    0
#define ACTION_UP      1
#define ACTION_MOVE    2
#define ACTION_CANCEL  3
#define ACTION_OUTSIDE 4
#define ACTION_MAX     0x0000FFFF
#define ACTION_MASK    ACTION_MAX

#define MOUSE_BUTTON_LEFT   0x00000000
#define MOUSE_BUTTON_RIGHT  0x00010000
#define MOUSE_BUTTON_MIDDLE 0x00020000
#define MOUSE_BUTTON_MASK   0x000F0000


inline Uint8 reg2mouseBtn(Uint32 reg)
{
    switch(reg & 0x000F0000)
    {
        case MOUSE_BUTTON_LEFT: return SDL_BUTTON_LEFT;
        case MOUSE_BUTTON_MIDDLE: return SDL_BUTTON_MIDDLE;
        default: return SDL_BUTTON_RIGHT;
    }
}

void Android_OnTouch(int reg, float x, float y, float p)
{
    if (!Android_Window)
        return;

    const action = reg & ACTION_MASK;

    if((action != ACTION_CANCEL) && (action != ACTION_OUTSIDE))
    {
        SDL_SetMouseFocus(Android_Window);
        switch(action)
        {
        case ACTION_MOVE:
            SDL_SendMouseMotion(Android_Window, 0, (int)x, (int)y);
            break;
        case ACTION_DOWN:
            SDL_SendMouseMotion(Android_Window, 0, (int)x, (int)y);
            SDL_SendMouseButton(Android_Window, SDL_PRESSED, reg2mouseBtn(reg));
            break;
        case ACTION_UP:
            SDL_SendMouseMotion(Android_Window, 0, (int)x, (int)y);
            SDL_SendMouseButton(Android_Window, SDL_RELEASED, reg2mouseBtn(reg));
            break;

        }
    }
    else
    {
        SDL_SetMouseFocus(NULL);
    }
}
